package cn.jolyoulu.adminweb.service.impl;


import cn.jolyoulu.adminweb.entity.vo.UserMenuVO;
import cn.jolyoulu.common.core.utils.draw.VerifyCodeUtils;
import cn.jolyoulu.common.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.jolyoulu.cmnservice.constant.ServiceRedisConstant;
import cn.jolyoulu.adminweb.entity.vo.DictSelectVO;
import cn.jolyoulu.adminweb.entity.vo.VerifyCodeImgVO;
import cn.jolyoulu.adminweb.service.ApiCommonService;
import cn.jolyoulu.cmnservice.entity.po.SysDictData;
import cn.jolyoulu.cmnservice.entity.po.SysDictType;
import cn.jolyoulu.cmnservice.serivce.SysDictDataService;
import cn.jolyoulu.cmnservice.serivce.SysDictTypeService;
import cn.jolyoulu.cmnservice.serivce.SysMenuService;
import cn.jolyoulu.cmnservice.utils.HoldUserUtils;
import cn.jolyoulu.common.web.enums.GlobalExpType;
import cn.jolyoulu.common.web.excption.GlobalException;

import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author LuZhouJin
 * @Date 2023/3/15
 */
@Slf4j
@Service
public class ApiCommonServiceImpl implements ApiCommonService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SysDictTypeService sysDictTypeService;

    @Autowired
    private SysDictDataService sysDictDataService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public VerifyCodeImgVO verifyCodeImg() {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        String id = UUID.randomUUID().toString();
        String code = VerifyCodeUtils.drawImage(bo);
        //将图片流转Base64
        String base64Image = Base64.getEncoder().encodeToString(bo.toByteArray());
        VerifyCodeImgVO res = new VerifyCodeImgVO()
                .setId(id)
                .setBase64Img("data:image/png;base64," + base64Image);
        String key = ServiceRedisConstant.getVerifycodeimg(id);
        redisUtils.set(key,code,30, TimeUnit.SECONDS);
        return res;
    }

    @Override
    public List<DictSelectVO> dictSelect(String dictType) {
        SysDictType sysDictType = sysDictTypeService.getByDictType(dictType);
        if (Objects.isNull(sysDictType)){
            throw new GlobalException(GlobalExpType.PARAM_ERROR);
        }
        List<SysDictData> sysDictData = sysDictDataService.selectByDictTypeId(sysDictType.getId());
        return sysDictData.stream().map(DictSelectVO::new).collect(Collectors.toList());
    }

    @Override
    public List<UserMenuVO> userMenu() {
        List<UserMenuVO> menuTree = new ArrayList<>();
        Set<String> roles = HoldUserUtils.get().getUserRoleIds();
        if (!roles.isEmpty()) {
            menuTree = sysMenuService.selectRolesMenuTree(roles, "0", UserMenuVO::new);
        }
        return menuTree;
    }
}
